#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'dengqianyi'

from fate.fateGenerate import FateGenerate
from shenbing.shenbing import Shenbing
import xlsReloadHelp
import json


class myEvents(object):
    def __init__(self):
        self._dict=dict()
        pass
    def onReceiveMessage(self,jsonObject):
        print "myEvents onReceiveMessage"
        for _index in xrange(0,len(self._dict["onReceiveMessage"])):
            self._dict["onReceiveMessage"][_index](jsonObject)
        pass
    def addEventCallback(self,key,callback):
        if self._dict.get(key) == None:
            self._dict[key] = list()
        self._dict[key].append(callback)
        return True
        pass

class Connection(object):
    _conns = set()
    _id = 0
    _events = myEvents()
    def __init__(self, stream, address):
        super(Connection,self).__init__()
        Connection._conns.add(self)
        Connection._id = Connection._id + 1
        self._stream = stream
        self._address = address
        self._stream.set_close_callback(self.on_close)
        self.read_message()
        print address, "A new user has entered the chat room.Connection id is",Connection._id

    def read_message(self):
        self._stream.read_until('\n', self._readMessages)

    def _readMessages(self, data):
        self._dataJsonObject = json.loads(str(data))
        Connection._events.onReceiveMessage(self._dataJsonObject)
        self._stream.write("Success!\n")
        self.read_message()

    def send_message(self, data):
        self._stream.write(data)
    def on_close(self):
        print self._address, "A user has left the chat room."
        Connection._conns.remove(self)
    @property
    def id(self):
        return Connection._id
    @classmethod
    def events(cls,self):
        return cls._events
    @classmethod
    def addEvents(cls,key,callback):
        cls._events.addEventCallback(key,callback)

def allInit():
    _fateGenerate = FateGenerate("fate/fate.xlsx","fate/fate_脚本输出.xlsx".decode('utf-8'))
    _reloadHelp = xlsReloadHelp.getInstance()
    _sbHelp = Shenbing("shenbing/shenbing_策划设计.xlsx".decode('utf-8'),"shenbing/shenbing_脚本输出.xlsx".decode('utf-8'))
    pass